package controller.v2;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;

import factory.DistributionLock;
import factory.RedisDistributionLock;
import model.GoodVO;
import model.OrderGoodVO;
import model.StandardVO;
import service.v2.ConfigService;
import service.v2.GoodService;
import service.v2.GoodTempService;
import service.v2.MemberChildService;
import service.v2.MemberService;
import service.v2.QRCodeService;
import service.v2.SplitService;
import util.ConfigUtil;
import util.ConverVideoUtils;
import util.DateParseUtil;
import util.DeliverUtil;
import util.HttpClientUtils;
import util.OssUtil;
import util.PackageUtil;
import util.PaypalPayment;
@Controller
@RequestMapping("/v2/test")
public class Test {
	@Autowired
	private SplitService splitService;
	@Autowired
	private GoodTempService goodTempService;
	@Autowired
	private QRCodeService qRCodeService;
	@Autowired
	private GoodService goodService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private MemberChildService memberChildService;
	@Autowired
	private static ConfigService configService;
	
	@Autowired
	@Qualifier("lockRedisTemplate")
    private RedisTemplate<Object, Object>  redisTemplate;
	
	@ResponseBody
	@RequestMapping("/processOpenId")
	public void aa(HttpServletRequest request) throws Exception {
//		String access_token = memberChildService.getAccessToken("err");
		List<Map<String,Object>> list = memberService.getOpenIdAll();
		
//		String token = "5_pwEH4NLvw3E4opEL9fjNUrT0DkoZ4UdBRMxFJmCLUEFPFwk4VmO_7FS_DygS47PFjT8-zusqguVR-idWc9DDqaf434DYWbVuoCFx2sbXxWg";
//		token = access_token;
//		Map map = new HashMap();
//		map.put("user_list", list);
		
//		String re = HttpClientUtils.sendHttpPost("https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token="+ token, JSON.toJSONString(map));
//		 System.out.println(re);
		for (Map<String, Object> m : list) {
			String re = HttpClientUtils.sendHttpGet("http://wap.uniplaza.com/login/getUnion.do?openid="+m.get("openid"));
//			String re = HttpClientUtils.sendHttpGet("http://10.0.1.41:8082/login/getUnion.do?openid="+m.get("openid"));
			System.out.println(m.get("openid"));
			if("0".equals(re)){
				re = null;
			}
			memberService.updateOpendIdBatch(m.get("openid").toString(), re);
		}
		
	}
	
	
	
	

	@RequestMapping(value="/linda",method=RequestMethod.GET) 
	public String linda() throws Exception{
		
		List<String> strArray = new ArrayList<String>();
		strArray.add("http://10.0.0.68:8080/v2/membercart/memberCartList");
		strArray.add("http://10.0.0.68:8080/v2/member/memberAward");
		strArray.add("http://10.0.0.68:8080/v2/member/levelupInfo");
		strArray.add("http://10.0.0.68:8080/v2/money/buyCash");
		strArray.add("http://10.0.0.68:8080/v2/money/unSettlement");
		strArray.add("http://10.0.0.68:8080/v2/money/incomeAndExpensesLog");
		strArray.add("http://10.0.0.68:8080/v2/money/withdrawDepositLog");
		strArray.add("http://10.0.0.68:8080/v2/money/withdrawDepositLogOne");
		strArray.add("http://10.0.0.68:8080/v2/msg/messageBox");
		strArray.add("http://10.0.0.68:8080/v2/msg/myAssets");
		strArray.add("http://10.0.0.68:8080/v2/friend/invitationFriend");
		strArray.add("http://10.0.0.68:8080/v2/page/noticeDetail");
		strArray.add("http://10.0.0.68:8080/v2/good/saleList");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("state", "200");
		map.put("msg", "successs");
		map.put("result", strArray);
		map.put("remark", "");
		return "/app/test/test";
		
		
		/*return PackageUtil.packageParams(200,"successs",arr,"");*/
		
	}
	
	
	
	public static void main(String[] args) {
			
			/*JSONObject  obj = new JSONObject();
			JSONObject  obj1 = new JSONObject();
			String openid = "oMP2Ts9aMnk0nBvF8XNVPsRO682Q";
			String content="aa";
			String access_token="6_BoNyzi98dFgimy7xiQfjU4hl63vBJRxHYN_UQYLfnyfbdyDFH9SYR_ceVMCLxV4pxy5-EFxk4QmNi6TPOylTyRGq0HAJ4iA6C3dZTzUGzff5nJkugrpVuHwCRxKYsaukhVcx67hWk875DhgIDNTcAFARBH";
			obj.put("touser", openid);
			obj.put("msgtype", "text");
			obj1.put("content", content);
			obj.put("text", obj1);
			String a = DeliverUtil.HttpRequest("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+access_token, HttpMethod.POST, "", obj.toJSONString());*/
		
			//JSONObject msg = JSONObject.parseObject(a);
			
		//String access_token = ((JSONObject) configService).getString("token");
		//System.out.println("access_token========"+access_token);
			String access_token="6_5eCKP06k1S7Rte76KSQi1Od1_DE4YWhS7eLjfzxpBQe3SCf5V4LKm7XnCEQba7F2ANtyM82Da7dRzHJmh_FXlNoXhBFFyHoCOvvrhhzdJevi5OigE-YFuC9vFrw26zgsg2UrPHU71qvIJX1gKGBdAIADZU";
			String getSendMsgUrl="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
			JSONObject  obj = new JSONObject();
			JSONObject  obj1 = new JSONObject();
			
			obj.put("touser","owGFR1Ohp-lSex2Z4N5DbdRm54NM");
			obj.put("msgtype","image");
			obj1.put("media_id","zB236e1vtmBRdcmVWzSQLJXXVEMz5lQ8Jlt3aweD8WA");
			obj.put("image",obj1);
			String a = DeliverUtil.HttpRequest(getSendMsgUrl+access_token, HttpMethod.POST, "", obj.toJSONString());
			JSONObject msg = JSONObject.parseObject(a);
			System.out.println(msg);
			
	}
	
	@ResponseBody
	@RequestMapping(value="/aa",method=RequestMethod.GET) 
	public String aa1(HttpServletRequest httpRequest,
			HttpServletResponse httpResponse) throws IOException{
		
	     AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", 
				ConfigUtil.ALIPAY_APP_ID, ConfigUtil.ALIPAY_APP_PRIVATE_KEY, "json", ConfigUtil.ALIPAY_CHARSET, ConfigUtil.ALIPAY_PUBLIC_KEY, "RSA2"); //获得初始化的AlipayClient
		AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
		alipayRequest.setReturnUrl("http://domain.com/CallBack/return_url.jsp");
		alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");//在公共参数中设置回跳和通知地址
		alipayRequest.setBizContent("{" +
		" \"out_trade_no\":\"20150320010101002\"," +
		" \"total_amount\":\"88.88\"," +
		" \"subject\":\"Iphone6 16G\"," +
		" \"product_code\":\"QUICK_WAP_PAY\"" +
		" }");//填充业务参数
		String form="";
		try {
		form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
		} catch (AlipayApiException e) {
		e.printStackTrace();
		}
		/*httpResponse.setContentType("text/html;charset=" +  ConfigUtil.ALIPAY_CHARSET);
		httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
		httpResponse.getWriter().flush();
		httpResponse.getWriter().close();*/
		    
		return form; 
	}
	
	@ResponseBody
	@RequestMapping(value="/ab",method=RequestMethod.GET) 
	public void ab(HttpServletRequest httpRequest,
			HttpServletResponse httpResponse)throws Exception{
//		qRCodeService.testTransanction();
		/*ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
		String str = opsForValue.get("name").toString();
		System.out.println(str);*/
	}
	
	@ResponseBody
	@RequestMapping(value="/abc",method=RequestMethod.GET) 
	public void abc(HttpServletRequest httpRequest,
			HttpServletResponse httpResponse)throws Exception{
		qRCodeService.test();
	}
	
	/**
	 * payssionPay测试
	 * @param request
	 * @param response
	 * @attr param payType 1 余额充值 
	 */
	@ResponseBody
	@RequestMapping("/payssionPay")																							
	public Object payssionPay(HttpServletRequest request, HttpServletResponse response) {
		
		System.out.println("==========================提示===========================");
		Map requestParams = request.getParameterMap();
		Set<Map.Entry> entrySet = requestParams.entrySet();
		for (Map.Entry entry : entrySet) {
			String key = (String) entry.getKey();
			String[] values = (String[]) entry.getValue();
			String value;
			try {
				value = transParamDecode(values[0], "UTF-8");
				System.out.println("==     key:"+key+"          value:"+value+"     ==");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}  
		System.out.println("=========================================================");
		return null;
	}
	private static String transParamDecode(String param, String charset) throws Exception {
		if (param == null) {
			return null;
		}
		return URLDecoder.decode(param, charset);
	}
	/*@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
        case 200:
            if (null != data) {
                PayResponse response = (PayResponse)data.getSerializableExtra(PayssionActivity.RESULT_DATA);
                if (null != response) {
                    //去服务端查询该笔订单状态，注意订单状态以服务端为准
                } else {
                    //should never go here
                }
            }
            break;
        case PayssionActivity.RESULT_CANCELED:
            //用户取消支付
            break;
        case PayssionActivity.RESULT_ERROR:
            //支付发生错误
            if (null != data) {
                //获取错误信息描述
                String des = data.getStringExtra(PayssionActivity.RESULT_DESCRIPTION);
                Log.v(this.getClass().getSimpleName(), "RESULT_ERROR" + des);
            }
            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }*/
	@ResponseBody
	@RequestMapping(value="/getStandardType",method=RequestMethod.GET) 
	public List<StandardVO> getStandardType(HttpServletRequest httpRequest,HttpServletResponse httpResponse)throws Exception{
	   List<StandardVO> typeList = goodTempService.getStandardType();
	   return typeList;
	}
	
	@ResponseBody
	@RequestMapping(value="/getStandardChild",method=RequestMethod.GET) 
	public List<StandardVO> getStandardChild(HttpServletRequest httpRequest,HttpServletResponse httpResponse,String type_id)throws Exception{
		List<StandardVO> childList = goodTempService.getStandardChild(type_id);
		return childList;
	}
	
	
	
	@RequestMapping(value="/video") 
	public void test(HttpServletRequest httpRequest,
			HttpServletResponse httpResponse)throws Exception{
		try {  
            // 转换并截图  
            String filePath = "D:\\Program Files\\VID_20141219_193309.mp4";  
            ConverVideoUtils cv = new ConverVideoUtils(filePath);  
            String targetExtension = ".wmv";  
            boolean isDelSourseFile = true;  
            boolean beginConver = cv.beginConver(targetExtension,isDelSourseFile);  
            System.out.println(beginConver);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
	}
	
	@ResponseBody
	@RequestMapping(value="/check",method=RequestMethod.GET) 
	public Object check(HttpServletRequest httpRequest,String testBody)throws Exception{
		DistributionLock r = new RedisDistributionLock(redisTemplate,"check");
		r.acquire();
		List<GoodVO> childList = goodTempService.check("1");
		r.release();
	
		System.out.println(httpRequest.getHeader("testHeader"));
		System.out.println(testBody);
		return PackageUtil.packageParams(200,"successs","test",""); 
	}
	
	@RequestMapping(value="/payment") 
	public void sofortPayment(String orderID) throws Exception {
		String total = "0.01";
		Payment payment = PaypalPayment.createPayment(total);
		for (Links links : payment.getLinks()) {
			if (links.getRel().equals("approval_url")) {
			}
		}
	}
}
